package com.example.carconsumer.controller.hkf;

import com.alibaba.dubbo.config.annotation.Reference;
import com.example.carinterface.pojo.User;
import com.example.carinterface.service.hkf.UserService;
import com.example.carinterface.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@CrossOrigin
@Api(value = "用户个人信息接口", tags = "个人中心API")
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference(check = false)
    UserService userService;

    @PostMapping("/updateUser")
    @ApiOperation(value = "用户详情修改", responseReference = "用户详情", httpMethod = "post", response = ResultJson.class)
    public ResultJson updateUser(@ApiParam(name = "User", value = "用户信息(需要用户的id 和修改的数据)", required = true) User user,
                                          @ApiParam(name = "file", value = "身份证照片", required = false) MultipartFile file,
                                          HttpServletRequest request){
        ResultJson resultJson=new ResultJson();
        if (file==null){ if (userService.updateUser(user)>0){
            return resultJson.setSuccess("修改成功");
        }else {
            return resultJson.setFail("修改失败");
        }}

        else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            String name=user.getName();
            // uploads文件夹位置
            String rootPath= ClassUtils.getDefaultClassLoader().getResource("").getPath();
//            String rootPath = request.getSession().getServletContext().getRealPath("download/idCard/");
            // 原始名称
            String originalFileName = file.getOriginalFilename();
            String substring = originalFileName.substring(originalFileName.lastIndexOf("."));//后缀名
            if (substring.equals(".jpg")||substring.equals(".png")){
                // 新文件名
                String newFileName = name + res + substring;
                // 创建年月文件夹
                Calendar date = Calendar.getInstance();
                File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));

                // 新文件
                File newFile = new File(rootPath + "/download/idCard/"+File.separator + dateDirs + File.separator + newFileName);
                // 判断目标文件所在目录是否存在
                if (!newFile.getParentFile().exists()) {
                    // 如果目标文件所在的目录不存在，则创建父目录
                    newFile.getParentFile().mkdirs();
                }


                // 将内存中的数据写入磁盘
                try {
                    file.transferTo(newFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }


                user.setIdCardUrl("download\\idCard"+ File.separator + dateDirs + File.separator + newFileName);
                System.out.println( "download"+ File.separator + dateDirs + File.separator + newFileName);
                if (userService.updateUser(user)>0){
                    return resultJson.setSuccess("修改成功");
                }else {
                    return resultJson.setFail("修改失败");
                }
            }
            else {
                return resultJson.setFail("添加失败,图片文件格式错误");
            }}


    }
    @GetMapping("/selectMyCoupon")
    @ApiOperation(value = "查询我的优惠卷", responseReference = "查询我的优惠劵", httpMethod = "get", response = ResultJson.class)
    public ResultJson selectMyCoupon(@ApiParam(name = "userId", value = "当前用户的userId", required = true)Integer userId){
        return   userService.selectMyCoupon(userId);
    }
    @PostMapping("/selectCouponUserCode")
    @ApiOperation(value = "兑换码搜索优惠卷", responseReference = "兑换码搜索优惠卷", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectCouponUserCode(@ApiParam(name = "code", value = "兑换码（code）", required = true) @RequestBody Map<String,Object> map)
    {
        return  userService.selectCouponUserCode(map);

    }
    @PostMapping("/insertMyCoupon")
    @ApiOperation(value = "领取到我的优惠劵", responseReference = "领取到我的优惠劵", httpMethod = "post", response = ResultJson.class)
    public ResultJson insertMyCoupon(@ApiParam(name = "code", value = "优惠劵id（couponId),当前用户id（userId），领取数量(myCouponNum(值同exchangeNum)),兑换码id(exchangeCodeId)", required = true) @RequestBody Map<String,Object> map)
    {
        return  userService.insertMyCoupon(map);

    }
    @PostMapping("/selectMyBusinessOrder")
    @ApiOperation(value = "查询我的订单", responseReference = "查询我的订单", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectMyBusinessOrder(@ApiParam(name = "userId", value = "当前用户id（userId）", required = true) @RequestBody Map<String,Object> map)
    {
        return  userService.selectMyBusinessOrder(map);

    }

    @PostMapping("/selectBanner")
    @ApiOperation(value = "查询轮播图", responseReference = "查询轮播图", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectBanner()
    {
        return  userService.selectBanner();

    }

    @PostMapping("/dianjiBanner")
    @ApiOperation(value = "点击轮播图", responseReference = "点击轮播图", httpMethod = "post", response = ResultJson.class)
    public ResultJson dianjiBanner(@ApiParam(name = "id", value = "轮播图id（id）", required = true) @RequestBody Map<String,Object> map)
    {
        return  userService.dianjiBanner(map);

    }

    @PostMapping("/selectUser")
    @ApiOperation(value = "查询用户信息（积分integral）", responseReference = "查询用户信息（积分integral）", httpMethod = "post", response = ResultJson.class)
    public ResultJson selectUser(@ApiParam(name = "id", value = "userId（id）", required = true) @RequestBody Map<String,Object> map)
    {
        return  userService.selectUser(map);

    }
}
